<template>
  <!-- 测试主容器 -->
  <div class="test-container">
    <!-- 加载中动画 -->
    <div v-if="loading || !isTestDataValid" class="loading-container">
      <div class="loading-spinner"></div>
      <p>loading...</p>
    </div>

    <template v-else>
      <!-- 普通选择题组件 -->
      <question-type-two :question="currentQuestionData" :questionNumber="currentQuestion" :totalQuestions="allQuestions.length" :progress="progressPercentage" @select-option="handleSelectOption" @next-question="nextQuestion" @prev-question="prevQuestion" />
    </template>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
import QuestionTypeTwo from '../components/QuestionTypeTwo.vue'

export default {
  name: 'Test',
  components: {
    QuestionTypeTwo,
  },
  data() {
    let qurey = this.$route.query
    return {
      uid: qurey.uid || localStorage.getItem('uid'),
      loading: false, // 是否处于加载状态
    }
  },
  computed: {
    // 映射全局状态
    ...mapState({
      currentQuestion: (state) => state.currentQuestion, // 当前题目编号
      questionsData: (state) => state.questionsData, // 题目数据
    }),
    ...mapGetters(['currentQuestionData', 'allQuestions', 'isLastQuestion']),
    // 检查测试数据是否有效
    isTestDataValid() {
      // 检查题目数据是否已加载
      return this.questionsData && this.questionsData.length > 0
    },
    // 当前题目的进度百分比
    progressPercentage() {
      if (!this.allQuestions || !this.allQuestions.length) return 0
      return Math.round((this.currentQuestion / this.allQuestions.length) * 100)
    },
  },
  methods: {
    // 映射actions和mutations
    ...mapActions(['fetchQuestionsData']),
    ...mapMutations(['setCurrentQuestion', 'addAnswer', 'resetTest']),

    // 处理用户选择的选项
    handleSelectOption(optionId, qId) {
      // 查找是否已存在该题的答案
      const existingAnswerIndex = this.$store.state.answers.findIndex((answer) => answer.index === this.currentQuestion - 1)

      // 如果已存在答案，先从数组中移除
      if (existingAnswerIndex !== -1) {
        this.$store.state.answers.splice(existingAnswerIndex, 1)
      }

      // 获取当前问题的完整数据，包括维度信息
      const currentQuestion = this.currentQuestionData

      // 获取所选选项对应的分数
      const score = currentQuestion.scores ? currentQuestion.scores[optionId] : 0

      // 记录新答案
      this.addAnswer({
        index: this.currentQuestion - 1, // 当前题目索引
        questionId: qId, // 当前题目的原始ID
        selectedOption: optionId, // 用户选择的选项ID
        score: score, // 所选选项的分数
        dimensions: currentQuestion.dimensions || [], // 题目涉及的维度
      })

      // 组件内部会调用nextQuestion方法
    },

    // 跳转到下一题或显示结果页
    async nextQuestion() {
      // 检查是否是整个测试的最后一题
      if (this.isLastQuestion) {
        // 导航到最终结果页面
        this.toResult()
        return
      }

      // 否则转到下一个问题
      this.setCurrentQuestion(this.currentQuestion + 1)
    },

    // 跳转到结果页
    toResult() {
      this.$router.replace({
        path: '/report',
        query: {
          uid: this.uid,
        },
      })
    },

    // 跳转到上一题
    prevQuestion() {
      if (this.currentQuestion > 1) {
        // 正常跳转到上一题
        this.setCurrentQuestion(this.currentQuestion - 1)
      }
    },
  },
  async created() {
    try {
      // 页面刷新时先等待数据加载
      this.loading = true

      // 如果已有题目数据，直接使用
      if (this.questionsData) {
        this.loading = false
        return
      }

      // 获取题目数据
      await this.fetchQuestionsData()

      // 等待Vue更新计算属性
      await this.$nextTick()
      this.loading = false
    } catch (error) {
      console.error('loading:', error)
      this.loading = false
    }
  },
}
</script>

<style scoped>
.test-container {
  background: #e2e4f5;
  min-height: 100vh;
}

.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  font-size: 16px;
  font-family: NotoSans;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #7b5cff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
